package com.cyz.admin.filter;

import com.alibaba.fastjson.JSON;
import com.cyz.common.enums.MyEnums;
import com.cyz.common.security.MyUserDetails;
import com.cyz.common.utils.*;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * token拦截器
 * 检查请求是否携带token
 * 覆盖security中filter验证token过滤器
 * 因为需要存取Redis，则重写
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

//    @Autowired
//    private RedisUtil redisUtil;
    @Autowired
    private MyRedisUtil myRedisUtil;

    /**
     * 白名单
     */
    public static final String[] WHITE_PATH = {
            "/user/login",
            "/swagger-resources/**",
            "/v3/**",
            "/swagger-ui/**"
    };

    /**
     *TODO
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取header里面的token
        String token = request.getHeader("token");
        //没有token，则放行，进行全面检查
        if(!StringUtils.hasText(token)) {
               if (PathMatchUtil.isMatcher(WHITE_PATH,request.getRequestURI())){
                   filterChain.doFilter(request,response);
                   return;
               }
                else{
                   WebUtils.renderString(response, JSON.toJSONString(R.error(MyEnums.NEED_LOGIN)));
                    return;
               }
        }
        //存在token，解析token,取出userId
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token超时  token非法
            //响应告诉前端需要重新登录
            WebUtils.renderString(response, JSON.toJSONString(R.error(MyEnums.NEED_LOGIN)));
            return;
        }
        String userId = claims.getSubject();
        //根据userId取出redis保存的用户信息
//        MyUserDetails adminUserDetails = redisUtil.getCacheObject(MyEnums.ADMIN_REDIS_NAME + userId);
        MyUserDetails adminUserDetails = (MyUserDetails) myRedisUtil.myStringGet(MyEnums.ADMIN_REDIS_NAME + userId);
//        Object cacheObject = redisCacheUtil.getCacheObject(SystemConstants.ADMIN_REDIS_NAME + userId);
//        System.out.println(cacheObject);
//        MyUserDetails adminUserDetails = (MyUserDetails) cacheObject;
        //信息为null
        if(Objects.isNull(adminUserDetails)){
            //说明登录过期  提示重新登录
            WebUtils.renderString(response, JSON.toJSONString(R.error(MyEnums.NEED_LOGIN)));
            return;
        }
        //验证成功，存入
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(adminUserDetails,null,null);
        //存入线程
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        //处理成功，放行
        filterChain.doFilter(request, response);
    }

}
